<template>
  <div class="comprehensive-table-container auto-height-container">
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item label="企业名称">
            <el-input v-model="queryForm.title" clearable placeholder="请输入企业名称"/>
          </el-form-item>

          <el-form-item>
            <el-button :loading="listLoading" native-type="submit" type="primary" @click="queryData">查询</el-button>

          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :span="24">
        <!--        <el-button :icon="Plus" type="primary" @click="handleAdd">添加</el-button>-->
        <!--        <el-button :icon="Delete" type="danger" @click="handleDelete">删除</el-button>-->
        <!--        <el-button type="primary" @click="handleDetail">详情</el-button>-->
        <!--        <el-button class="hidden-xs-only" type="primary" @click="handleDetailStayTable">后台打开详情</el-button>-->
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table ref="tableRef" v-loading="listLoading" border :data="list">
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务ID" min-width="100" prop="uid"/>
      <el-table-column align="center" label="企业名称" prop="company_name"/>
<!--      <el-table-column align="center" label="使用系统提示词" prop="author"/>-->
<!--      <el-table-column align="center" label="使用用户提示词" prop="author"/>-->


      <el-table-column align="center" label="任务状态" min-width="100">
        <template #default="{ row }">
          <el-tag effect="dark" type="primary" v-if="row.status==1" >
            已完成
          </el-tag>

          <el-tag effect="dark" type="warning" v-if="row.status==0" >
            进行中
          </el-tag>

          <el-tag effect="dark" type="danger" v-if="row.status==2" >
            任务失败
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="nickname"/>

      <el-table-column align="center" label="创建时间" min-width="160" prop="create_time_name"/>
      <el-table-column align="center" label="操作" width="215">
        <template #default="{ row }">
          <el-button text type="primary" v-if="row.status==1" @click="handleDetail(row)">详情</el-button>
          <el-button text type="primary" v-if="row.status==1" @click="del(row.id)">删除</el-button>

        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据"/>
      </template>
    </el-table>
    <vab-pagination
      :current-page="queryForm.pageNo"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <default-table-edit ref="editRef" @fetch-data="fetchData"/>
  </div>
</template>

<script lang="ts" setup>
import {Delete, Plus, Search} from '@element-plus/icons-vue'
import type {TableInstance} from 'element-plus'
import {useRoutesStore} from '/@/store/modules/routes'
import {useTabsStore} from '/@/store/modules/tabs'
import {handleMatched, handleTabs} from '/@/utils/routes'
import {getHistory,doDelete} from '/@/api/company'

defineOptions({
  name: 'DefaultTable',
})

const router = useRouter()
const routesStore = useRoutesStore()
const {getAllRoutes: allRoutes} = storeToRefs(routesStore)
const tabsStore = useTabsStore()
const {changeTabsMeta, addVisitedRoute} = tabsStore
const editRef = ref<any>(null)
const tableRef = ref<TableInstance>()
const fold = ref<boolean>(true)
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const total = ref<number>(0)
const selectRows = ref<any>([])
const queryForm = reactive<any>({
  pageNo: 1,
  pageSize: 20,
})

const fetchData = async () => {
  listLoading.value = true
  const {data} = await getHistory(queryForm)
  list.value = data.data
  total.value = data.total
  listLoading.value = false
}

const handleSizeChange = (value: number) => {
  queryForm.pageNo = 1
  queryForm.pageSize = value
  fetchData()
}

const handleCurrentChange = (value: number) => {
  queryForm.pageNo = value
  fetchData()
}

const queryData = () => {
  queryForm.pageNo = 1
  fetchData()
}

const statusFilter = (status: string | number) => {
  const statusMap: any = {
    published: 'success',
    draft: 'primary',
    deleted: 'danger',
  }
  return statusMap[status]
}

const handleFold = () => {
  fold.value = !fold.value
}

const setSelectRows = (value: string) => {
  selectRows.value = value
}

const handleAdd = () => {
  editRef.value.showEdit()
}

const handleEdit = (row = {}) => {
  editRef.value.showEdit(row)
}

const handleDelete = (row: any) => {
  if (row.id) {
    $baseConfirm('您确定要删除当前项吗', null, async () => {
      const {msg}: any = await doDelete({ids: row.id})
      $baseMessage(msg, 'success', 'hey')
      await fetchData()
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { id: any }) => item.id).join(',')
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const {msg}: any = await doDelete({ids})
        $baseMessage(msg, 'success', 'hey')
        await fetchData()
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}

const handleDetailStayTable = async () => {
  if (selectRows.value.length === 1)
    for (let i = 0; i < selectRows.value.length; i++) {
      const matched = handleMatched(allRoutes.value, '/vab/table/defaultTableDetail')
      const tab = handleTabs({
        ...matched.at(-1),
        query: selectRows.value[i],
      })
      if (tab) {
        await addVisitedRoute(tab)
        await changeTabsMeta({
          title: '详情页',
          meta: {
            title: `${tab.query.title} 详情页`,
          },
        })
      }
    }
  else $baseMessage('请选择一行进行详情页跳转', 'warning', 'hey')
}

const del = (id: number) => {
  $baseConfirm('您确定要删除当前项吗', null, async () => {
    const {msg}: any = await doDelete({id: id})
    $baseMessage(msg, '删除成功!', 'hey')
    await fetchData()
  })
}
const handleDetail = (row: any) => {
  if (row.id)
    router.push({
      path: '/historySearch/companyDetail',
      query: {
        id: row.id,
        timestamp: Date.now(), //允许同一个详情页同时打开多次，否则会触发路由被缓存下次无法刷新的bug
      },
    })

}

onActivated(() => {
  tableRef.value?.doLayout()
})

onBeforeMount(() => {
  fetchData()
})
</script>
